import {
	withState,
	withHandlers,
	compose,
	lifecycle
} from "recompose"
import {postParam} from "../../../../shared/server"
import {env, DEV, defaultRouter} from "../../../../shared/project-config"


const devData = env === DEV ? {
	userName: 'xiaop0817',
	password: '123456'
} : {}

const formCompose = compose(
	withState('_initData', '_setInitData', () => {
		const passwordAccount = localStorage.getItem('passwordAccount')
		if (passwordAccount) {
			return Object.assign(devData, {userName: passwordAccount, remember: true})
		}
		return devData
	}),
	//密码登录接口信息
	withState('_serverMessage', '_setServerMessage', null),
	withHandlers({
		onSubmit: ({_setSubmitting, _setServerMessage, history}) => {
			return (form) => {
				_setSubmitting(true)
				const submit = (values) => {
					const remember = values.remember
					postParam('/auth/login', values, true)
						.then(() => {
							const redirect = localStorage.getItem('redirect_url')
							if (remember) {
								localStorage.setItem('passwordAccount', values.userName)
							} else {
								localStorage.removeItem('passwordAccount')
							}

							if (redirect) {
								localStorage.removeItem('redirect_url')
								window.location = redirect
								return
							}
							history.push(defaultRouter)
						})
						.catch(e => {
							if (e) _setServerMessage(e.message)
						})
						.finally(() => {
							_setSubmitting(false)
						})
				}
				form.validateFields()
					.then(submit)
					.catch(() => {
						_setSubmitting(false)
					})
			}
		}
	}),
	withHandlers({
		onEnterKey: ({onSubmit}) => {
			return (form) => {
				onSubmit(form)
			}
		},
		onInputChange: ({setAvatar}) => {
			return (event) => {
				const localAvatar = localStorage.getItem(`${event.target.value}_avatar`)
				if (localAvatar && localAvatar !== 'null') {
					setAvatar(localAvatar)
				}
			}
		}
	}),
	lifecycle({
		componentDidMount() {
			const {setAvatar} = this.props
			const passwordAccount = localStorage.getItem('passwordAccount')
			const localAvatar = localStorage.getItem(`${passwordAccount}_avatar`)
			if (localAvatar && localAvatar !== 'null') {
				setAvatar(localAvatar)
			}
		}
	})
)

export default formCompose